$(function () {
    var $image = $('#image')

    const options = {
        aspectRatio: 1,
        preview: '.img-preview'
    }
    $('#image').cropper(options)
    $('#chooseImageBtn').on('click', function () {
        $('#chooseImageInp').click()
    })

    // 渲染图片 change 选择文件的时候触发的事件,value值发生改变就会触动
    $('#chooseImageInp').on('change', function () {
        // console.log(this.value);
        let file = this.files[0]

        if (file === undefined) {
            return layui.layer.msg('上传头像,不能为空')
        }
        let url = URL.createObjectURL(file)
        console.log(url);
        $image.cropper('destroy')
            .attr('src', url)
            .cropper(options)
    })
    $('#uploadBtn').on('click', function () {

        var dataURL = $image
            .cropper('getCroppedCanvas', {
                width: 100,
                height: 100
            })
            .toDataURL('image/png')
            // console.log(dataURL);
        axios({
            method: 'POST',
            url: '/my/update/avatar',
            data: 'avatar=' + encodeURIComponent(dataURL)
        }).then(res => {
            if (res.data.status !== 0) {
                return layui.layer.msg(res.data.message)
            }
            console.log(res);
            layui.layer.msg('修改成功')
            window.parent.getUserInfo()
        })
    })

})